package com.hanshushi_jiekou;

import java.util.ArrayList;
import java.util.function.Predicate;

public class PredicateDemo {
    public static void main(String[] args) {
        boolean b1 = checkString("hello", s -> s.length() > 8);
        System.out.println(b1);
        boolean b2 = checkString("helloworld", s -> s.length() > 8);
        System.out.println(b2);
        System.out.println("----------------------------");
        boolean b3 = checkString("hello", s -> s.length() > 8, s -> s.length() < 15);
        System.out.println(b3);
        boolean b4 = checkString("helloworld", s -> s.length() > 8, s -> s.length() < 15);
        System.out.println(b4);
        System.out.println("----------------------------");

        // 案例
        String[] arr = {"林青霞,30", "柳岩,34", "张曼玉,35", "貂蝉,31", "王祖贤,33"};
        ArrayList<String> strings = filterCondition(arr,
                s -> s.split(",")[0].length() > 2,
                s -> Integer.parseInt(s.split(",")[1]) > 33);
        for (String a : strings) {
            System.out.println(a);
        }

    }

    // 判断给定的字符串是否满足要求
    private static boolean checkString(String s, Predicate<String> pre) {
        // return pre.test(s);
        // 取非操作
        // return !pre.test(s);
        // 等价于
        return pre.negate().test(s);
    }

    // 同一个字符串给出两个不同的判断条件，最后把这两个判断结果做逻辑与(或)，返回最终结果
    private static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2) {
        // 进行逻辑与 and
        // return pre1.and(pre2).test(s);
        // 进行逻辑或 or
        return pre1.or(pre2).test(s);
    }

    private static ArrayList<String> filterCondition(String[] array, Predicate<String> pre1, Predicate<String> pre2) {
        ArrayList<String> arr = new ArrayList<String>();
        for (String s : array) {
            if (pre1.and(pre2).test(s)) {
                arr.add(s);
            }
        }
        return arr;
    }
}
